package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.PageResult;
import com.itheima.pojo.Student;
import com.itheima.pojo.StudentQueryParam;
import com.itheima.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    @Override
    public PageResult<Student> page(StudentQueryParam studentQueryParam) {
        // 开启一条分页查询
        PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());
        List<Student> stuList = studentMapper.page(studentQueryParam);
        Page<Student> p = (Page<Student>) stuList;
        return new PageResult<>(p.getTotal(), p.getResult());
    }

    @Override
    public void delete(List<Integer> ids) {
        studentMapper.delete(ids);
    }

    @Override
    public void saveStudent(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.saveStudent(student);
    }

    @Override
    public Student findById(Integer id) {
        return studentMapper.findById(id);
    }

    @Override
    public void updateStudent(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.updateStudent(student);
    }

    @Override
    public void punishment(Integer id, Integer score) {
        // 1.先查询到学生当前的违纪次数和违纪分数
        Map<String, Integer> violation = studentMapper.violationScore(id);
        // 2.增加违纪的分数,然后更新回去
        Student student = new Student();
        student.setId(id);
        student.setUpdateTime(LocalDateTime.now());
        student.setViolationCount((short) (violation.get("violationCount") + 1));
        student.setViolationScore((short) (violation.get("violationScore") + score));
        studentMapper.updateStudent(student);
    }
}
